package com.wenqiner.requesttool.core.tool;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.TreeMap;

/**
 * 排序map
 *
 * @author: rhf
 * @date: 2022-06-10
 **/
public class StoreMapJsonSerializer extends JsonSerializer<LinkedHashMap> {
    @Override
    @SuppressWarnings("all")
    public void serialize(LinkedHashMap map, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (null == map) {
            jsonGenerator.writeNull();
            return;
        }

        if (!map.isEmpty()) {
            TreeMap<String, Object> storeMap = new TreeMap<>();
            map.keySet().stream()
                    .filter(key -> null != map.get(key))
                    .sorted(String.CASE_INSENSITIVE_ORDER)
                    .forEach(key ->
                            storeMap.put(key.toString(), map.get(key)));
            jsonGenerator.writeObject(storeMap);
        } else {
            jsonGenerator.writeObject(map);
        }
    }
}
